package io.renren.modules.wangeditor;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @program: stf
 * @description:
 * @author: Custom
 * @create: 2018-10-21 18:01
 **/
//@RestController
public class WangEditorController {

    private static final int ICON = 0;
    private static final int SLIDESHOW = 1;
    private static final int USERIMG = 2;


    //图片上传
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public WangEditor upload(MultipartFile myFileName, HttpSession session, HttpServletRequest request, HttpServletResponse response,@RequestParam int type) throws IOException {
        String realName = "";
        if (myFileName != null) {
            String fileName = myFileName.getOriginalFilename();
            String fileNameExtension = fileName.substring(fileName.indexOf("."), fileName.length());
            // 生成实际存储的真实文件名

            realName = UUID.randomUUID().toString() + fileNameExtension;

            // "/upload"是你自己定义的上传目录

            File uploadFile = new File("D:/upload", realName);
//            File uploadFile = new File("D:/upload", realName);
            myFileName.transferTo(uploadFile);
        }
//        String str = request.getContextPath() + "/upload/" + realName;
        String str = "D:/upload/" + realName;
        WangEditor wangEditor = new WangEditor();
        wangEditor.getData().add(str);
        return wangEditor;
    }

    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            System.out.println("创建目录" + destDirName + "失败，目标目录已经存在");
            return true;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        //创建目录
        if (dir.mkdirs()) {
            System.out.println("创建目录" + destDirName + "成功！");
            return true;
        } else {
            System.out.println("创建目录" + destDirName + "失败！");
            return false;
        }
    }

}
